package com.bbzn.user.client.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class MayiktJwtUtils {

    public static final String TOKEN_HEADER = "token";
    public static final String TOKEN_PREFIX = "Bearer ";

    private static final String SUBJECT = "mayikt";

    private static final long EXPIRITION = 1000 * 24 * 60 * 60 * 7;

    private static final String APPSECRET_KEY = "secret";

    private static final String ROLE_CLAIMS = "roles";

    private static final String HEADER = "Authorization";

    private static final String PREFIX = "Bearer";

    private static final String LANGUAGE = "language";

    /**
     * 获取用户名
     *
     * @param request
     * @return
     */
    public static String getUsername(HttpServletRequest request, String secretKey) {
        String token = request.getHeader(HEADER).replace(PREFIX + " ", "");
        Claims claims = Jwts.parser()
                .setSigningKey(secretKey.getBytes())
                .parseClaimsJws(token)
                .getBody();
        return  claims.getSubject();
    }

    /**
     * 获取语言
     *
     * @param secretKey
     * @return
     */
    public static String getLanguage(HttpServletRequest request, String secretKey) {
        String token = request.getHeader(HEADER).replace(PREFIX + " ", "");
        Claims claims = Jwts.parser()
                .setSigningKey(secretKey.getBytes())
                .parseClaimsJws(token)
                .getBody();
        return claims.get(LANGUAGE).toString();
    }



    /**
     * 是否过期
     *
     * @param token
     * @return
     */
    public static boolean isExpiration(String token) {
        Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
        return claims.getExpiration().before(new Date());
    }

}
